<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { useAddOrDelBlackList, useAddorDelStock } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { useUserStore } from '@fl/store/modules/user'
import { cloneDeep } from 'lodash-es'

import { formTypeEnum } from './constant'

const { isPending: addOrDelStockPending, mutate: addOrDelStockMutate } = useAddorDelStock()
const { isPending: addOrDelBlackListPending, mutate: addOrDelBlackListMutate } = useAddOrDelBlackList()

const loading = computed(() => addOrDelStockPending.value || addOrDelBlackListPending.value)

const userStore = useUserStore()

// const cascaderProps = { checkStrictly: true, emitPath: false, multiple: true }

// const serviceCategoryOptions = defineModel<any>('serviceCategoryOptions')

// const cascaderOpitons: any = computed(() => {
//     return serviceCategoryOptions.value ? toRaw(serviceCategoryOptions.value) : []
// })

const id = defineModel<string | undefined>('id')

const buyerId = defineModel<any>('buyerId')

const type = defineModel<any>('type')

const buyerList = defineModel<any>('buyerList')

const wareHouseName = defineModel<any>('wareHouseName')

const supplierCategory = defineModel<any>('supplierCategory')

const visible = defineModel<boolean>('visible', { required: true })

const formRef = ref()

const state = ref<any>(
    { buyerId: '', file: [], supplierCategory: supplierCategory.value, wareHouseName: wareHouseName.value },
)

const buyerOptions = computed(() => cloneDeep(unref(buyerList)))

const warehouseColumns: PlusColumn[] = [
    {
        label: '入库供应商',
        prop: 'wareHouseName',
        valueType: 'text',
    },
    {
        label: '采购商',
        options: buyerOptions,
        prop: 'buyerId',
        valueType: 'select',
    },
    {
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 500,
            showWordLimit: true,
        },
        label: '供应商入库说明',
        prop: 'remark',
        valueType: 'textarea',
    },
    {
        label: '供应商类别',
        prop: 'supplierCategory',
        valueType: 'text',
    },
    {

        label: '附件',
        prop: 'file',
    },
    {
        label: '操作人',
        prop: 'operateName',
        valueType: 'text',
    },
]

const removeColumns: PlusColumn[] = [
    {
        label: '供应商',
        prop: 'wareHouseName',
        valueType: 'text',
    },
    {
        fieldProps: {
            disabled: true,
        },
        label: '采购商',
        options: buyerOptions,
        prop: 'buyerId',
        valueType: 'select',
    },
    {
        label: '操作人',
        prop: 'operateName',
        valueType: 'text',
    },
    {
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 500,
            showWordLimit: true,
        },
        label: '移出供应商库说明',
        prop: 'remark',
        valueType: 'textarea',
    },
    {
        label: '附件',
        prop: 'file',
    },
]

const addtoblacklistColumns: PlusColumn[] = [
    {
        label: '供应商',
        prop: 'wareHouseName',
        valueType: 'text',
    },

    {
        fieldProps: {
            disabled: true,
        },
        label: '采购商',
        options: buyerOptions,
        prop: 'buyerId',
        valueType: 'select',
    },
    {
        label: '操作人',
        prop: 'operateName',
        valueType: 'text',
    },
    {
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 500,
            showWordLimit: true,
        },
        label: '新增黑名单说明',
        prop: 'remark',
        valueType: 'textarea',
    },
    {
        label: '附件',
        prop: 'file',
    },
]

const removefromblacklistColumns: PlusColumn[] = [
    {
        label: '供应商',
        prop: 'wareHouseName',
        valueType: 'text',
    },

    {
        fieldProps: {
            disabled: true,
        },
        label: '采购商',
        options: buyerOptions,
        prop: 'buyerId',
        valueType: 'select',
    },
    {
        label: '操作人',
        prop: 'operateName',
        valueType: 'text',
    },
    {
        fieldProps: {
            autosize: { maxRows: 4, minRows: 2 },
            maxlength: 500,
            showWordLimit: true,
        },
        label: '移出黑名单说明',
        prop: 'remark',
        valueType: 'textarea',
    },
    {
        label: '附件',
        prop: 'file',
    },
]

const columns = computed(() => {
    if (type.value === formTypeEnum.warehouse) {
        return warehouseColumns
    }
    if (type.value === formTypeEnum.remove) {
        return removeColumns
    }
    if (type.value === formTypeEnum.addtoblacklist) {
        return addtoblacklistColumns
    }
    if (type.value === formTypeEnum.removefromblacklist) {
        return removefromblacklistColumns
    }
    return []
})

const rules = {
    buyerId: [
        {
            message: '请选择采购商',
            required: true,
        },
    ],
    remark: [
        {
            message: '请输入说明',
            required: true,
        },
    ],
    supplierCategory: [
        {
            message: '请先去完善供应商类别信息',
            required: true,
        },
    ],
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = undefined
    wareHouseName.value = ''
    formRef.value.formInstance.resetFields()
}

function addOrDelStock(stockType: '入库' | '移出供应商库') {
    const params = {
        supplierId: id.value,
        ...state.value,
        catType: 1,
        file: JSON.stringify(state.value.file),
        type: stockType,
    }
    delete params.supplierCategory
    console.log(params, 'params')
    addOrDelStockMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            cancel()
        },
    })
}

function addOrDelBlackList(blackType: '加入黑名单' | '移出供应商库') {
    const params = {
        supplierId: id.value,
        ...state.value,
        file: JSON.stringify(state.value.file),
        type: blackType,
    }
    addOrDelBlackListMutate(params, {
        onSuccess: () => {
            ElMessage.success('操作成功')
            cancel()
        },
    })
}

// function handleChange(e: any) {
//     console.log(e, 'e')
//     // state.value.categoryName = e
// }

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        if (type.value === formTypeEnum.warehouse || type.value === formTypeEnum.remove) {
            return addOrDelStock(type.value)
        }
        if (type.value === formTypeEnum.addtoblacklist || type.value === formTypeEnum.removefromblacklist) {
            return addOrDelBlackList(type.value)
        }
    }
}
watchEffect(() => {
    if (wareHouseName.value) {
        state.value.wareHouseName = wareHouseName.value
    }
    if (buyerId.value) {
        state.value.buyerId = buyerId.value
    }
    state.value.operateName = userStore.getUserInfo?.sysUser?.userName || ''
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="type"
                width="800"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <PlusForm ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="140"
                  :rules="rules"
                  :has-footer="false"
        >
            <!-- <template #plus-field-categoryName>
                <el-cascader v-model="state.categoryName"
                             :options="cascaderOpitons"
                             :props="cascaderProps"
                             clearable
                             filterable
                             :show-all-levels="false"
                             class="w-full"
                             placeholder="请选择供应商分类"
                             @change="handleChange($event)"
                />
            </template> -->
            <template #plus-field-supplierCategory>
                {{ state.supplierCategory || '暂无数据' }}
            </template>

            <template #plus-field-file>
                <FlUpload v-model="state.file"
                          list-type="text"
                          :limit="10"
                          accept=".rar,.zip,.pdf,.docx,.jpg,.jepg,.png,.xlsx"
                          :file-size="10"
                          :tips="true"
                          :is-mall-admin="true"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="loading"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
